<script setup>
import { ref, onMounted, computed } from 'vue'
import { sessionApi, treeDictsApi, pageFeedsApi, repliedFeedsApi, saveFeedApi, oneFeedApi, proFeedsApi } from '@/commons/api'
import routes from '@/commons/router'
import TreeSel from '@/components/cascader/TreeSel'
import Loader from '@/components/loader/Loader'
import { CScrollbar } from 'c-scrollbar'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import Pager from '@/components/pager/Pager'
import { formatDate } from '@/commons/filter'
import SelFile from '@/components/upload/SelFile'

const loadShow = ref(false)

const glbPid = '111111111111111111111'

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

let procAuth = {
  saveAuth: false,
  delAuth: false,
  passAuth: false
}
// checkAuth 获取权限
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if (res.code === import.meta.env.VITE_SUCCESS_CODE) {
      const userBtnCode = res.data.btnCodes
      procAuth = {
        saveAuth: userBtnCode.indexOf('1001011201') !== -1,
        delAuth: userBtnCode.indexOf('1001011202') !== -1,
        passAuth: userBtnCode.indexOf('1001011203') !== -1
      }
      await selTypes()
      await pages(0, 1)
    } else {
      localStorage.removeItem("token")
      Msg({ kind: 'error', txt: res.msg })
      routes.replace('/login')
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// 所有菜单数组
const typeList = ref([])
// selTypes 获取菜单及按钮列表
const selTypes = async () => {
  const res = await treeDictsApi({ kind: 2, typeCode: 'FEEDBACK' })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    typeList.value = res.data
  }
}

const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.fbType = item.selId
      schRef.value.typeName = item.selName
      schRef.value.typeCode = item.selCode
      break
    case 2:
      fbForm.value.fbType = item.selId
      fbForm.value.typeName = item.selName
      fbForm.value.typeCode = item.selCode
      break
  }
}

const schRef = ref({
  keywords: '',
  fbType: '',
  typeName: '',
  typeCode: '',
  offset: 0,
  limit: 20
})
const total = ref(0)
const curPage = ref(1)
const fbList = ref([])
const hasData = ref(false)
// pages 列表展示
const pages = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageFeedsApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    fbList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    keywords: '',
    fbType: '',
    typeName: '',
    typeCode: '',
    offset: 0,
    limit: 20
  }
  pages(0, 1)
}

// 选择效果实现
const idList = ref([])
const checkList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    fbList.value.forEach(item => {
      idList.value.push(item.fbId)
      checkList.value.push(true)
    })
  } else {
    fbList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, roleId) => {
  if(!checkList.value[idx]) {
    idList.value.push(roleId)
  } else {
    idList.value.splice(idList.value.findIndex(id => id === roleId), 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const fbObj = {
  fbId: '',
  phone: '',
  email: '',
  imgIds: '',
  imgNames: '',
  imgUrls: '',
  fbType: '',
  typeName: '',
  typeCode: '',
  kind: 0,
  parentId: '',
  remarks: ''
}
const fbForm = ref(fbObj)
// add 新增
const oneModalShow = ref(false)
const add = (kind, parentId) => {
  fbForm.value.kind = kind
  fbForm.value.parentId = parentId
  oneModalShow.value = true
}
// update 修改
const imgListRef = ref([])
const update = async (fbId) => {
  const res = await oneFeedApi({ fbId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    oneModalShow.value = true
    fbForm.value = res.data
    // 加载多附件
    imgListRef.value = []
    if(fbForm.value.imgIds && fbForm.value.imgIds!=='') {
      let fileIdArr = fbForm.value.imgIds.split(',')
      let fileNameArr = fbForm.value.imgNames.split(',')
      let fileUrlArr = fbForm.value.imgUrls.split(',')
      for(let i=0, c=fileIdArr.length; i<c; i++) {
        if(fileIdArr[i] && fileIdArr[i]!=='') {
          imgListRef.value.push({id: fileIdArr[i], name: fileNameArr[i], url: fileUrlArr[i]})
        }
      }
    }
  } else {
    Msg({ kind: 'info', txt: '暂无内容' })
  }
}

// reply 回复意见
const replyModalShow = ref(false)
const reply = (fbType, kind, parentId) => {
  replyModalShow.value = true
  fbForm.value.fbType = fbType
  fbForm.value.kind = kind
  fbForm.value.parentId = parentId
  fbForm.value.phone = '18173330471'
  fbForm.value.email = 'henry728@163.com'
}

// save 保存提交
const save = async (kind) => {
  let phone = fbForm.value.phone
  let email = fbForm.value.email
  let fbType = fbForm.value.fbType
  let remarks = fbForm.value.remarks
  if(phone === '' || phone.length < 7 || phone.length > 13) {
    Msg({ kind: 'warn', txt: '联系电话不能为空！' })
    return
  } else if(email === '' || email.length > 100) {
    Msg({ kind: 'warn', txt: '电子邮箱不能为空，且长度不超过100个字符！' })
    return
  } else if(remarks === '' || remarks.length > 100) {
    Msg({ kind: 'warn', txt: '意见内容不能为空，且长度不超过150个汉字！' })
    return
  } else if(fbType === '' || fbType.length !== 21) {
    Msg({ kind: 'warn', txt: '请选择意见分类！' })
    return
  }
  // 设置多图
  let imgIds='', imgNames='', imgUrls=''
  imgListRef.value.forEach(curImg => {
    imgIds += curImg.id + ','
    imgNames += curImg.name + ','
    imgUrls += curImg.url + ','
  })
  imgIds = imgIds.substring(0, imgIds.length-1)
  imgNames = imgNames.substring(0, imgNames.length-1)
  imgUrls = imgUrls.substring(0, imgUrls.length-1)
  fbForm.value.imgIds = imgIds
  fbForm.value.imgNames = imgNames
  fbForm.value.imgUrls = imgUrls
  loadShow.value = true
  try {
    const res = await saveFeedApi(fbForm.value)
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      closeModal(kind)
      await pages(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，按钮信息保存成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = (kind) => {
  imgListRef.value = []
  fbForm.value = fbObj
  switch (kind) {
    case 1:
      oneModalShow.value = false
      break
    case 2:
      replyModalShow.value = false
      break
  }
}

// process 处理
const process = async(states) => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再处理！' })
    return
  }
  Confirm('确定要处理选中的按钮吗？').then(() => {
    procFeeds(states)
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消删除选中的数据！" })
  })
}
// procFeeds 处理实现，分离出来防止调用时异步报错
const procFeeds = async (states) => {
  let fbIds = idList.value.join(',')
  loadShow.value = true
  try {
    const res = await proFeedsApi({ states, fbIds })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await pages(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，意见反馈信息处理成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const replied = async (parentId, index) => {
  if(!fbList.value[index].children || fbList.value[index].children.length===0) {
    loadShow.value = true
    try {
      const res = await repliedFeedsApi({ parentId })
      if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
        fbList.value[index].children = res.data
      } else {
        fbList.value[index].children = []
      }
      loadShow.value = false
    } catch (e) {
      loadShow.value = false
      Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
    }
  }
}

// 附件赋值
const setUrl = (kind, type, file) => {
  imgListRef.value = file
}

// fmtDate 时间戳转时间
const fmtDate = computed(() => {
  return (time, kind) => {
    let date = new Date(time*1000)
    return formatDate(date, kind)
  }
})
</script>

<template>
  <div class="fb-a">
    <div class="fb-b">
      <div class="fb-c">
        <div class="mr15" @click="checkAll()" title="全选"><i :class="['iconfont', allCheck ? 'chked' : 'chk']" v-html="allCheck ? '&#xea3a;' : '&#xea46;'" /></div>
        <div v-if="procAuth.saveAuth" class="btn-pi mr15" title="新增" @click="add(1, glbPid)"><i class="iconfont">&#xea2d;</i> 新增</div>
        <div v-if="procAuth.delAuth" class="btn-de mr15" title="删除" @click="process(2)"><i class="iconfont">&#xea45;</i> 删除</div>
        <div v-if="procAuth.passAuth" class="btn-ds mr15" title="启用" @click="process(1)"><i class="iconfont">&#xea30;</i> 启用</div>
        <div v-if="procAuth.passAuth" class="btn-dw mr15" title="停用" @click="process(3)"><i class="iconfont">&#xea2e;</i> 停用</div>
        <div class="btn-r mr15" title="筛选" @click="search"><i class="iconfont">&#xea49;</i></div>
        <div class="btn-r mr15" title="刷新" @click="pages(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="fb-d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 系统管理 > 意见反馈</div>
    </div>
    <div v-show="schShow" class="fb-e">
      <div class="mr15 mt10"><tree-sel :kind="1" :tree-list="typeList" :inboxed="true" :curName="schRef.typeName!=='' ? schRef.typeName+'['+schRef.typeCode+']' : ''" pre-name="意见分类" @setValue="setValue" /></div>
      <div class="mr15 mt10"><input type="text" v-model="schRef.keywords" maxlength="30" placeholder="请输入关键字" class="sch-ipt" /></div>
      <div class="fb-f mt10">
        <div class="btn-pi mr15" title="搜索" @click="pages(0, 1)"><i class="iconfont">&#xea8e;</i> 搜索</div>
        <div class="btn-d" title="重置" @click="clrSch"><i class="iconfont">&#xea4f;</i> 重置</div>
      </div>
    </div>
    <div v-if="hasData" class="fb-g">
      <div class="fb-h" v-for="(item, index) in fbList" :key="item.fbId">
        <div class="fb-i">{{ item.remarks }}</div>
        <div class="fb-j">
          <div class="mr15"><i @click="checkCurId(index, item.fbId)" :class="['iconfont', checkList[index]  ? 'chked' : 'chk']" v-html="checkList[index]  ? '&#xe685;' : '&#xe686;'"></i></div>
          <div class="mr15">{{ item.nickName }}</div>
          <div class="mr15"><span :class="[item.states===1 ? 'tag-s' : 'tag-w']">{{ item.states===1 ? '已启用' : '已停用' }}</span></div>
          <div class="fb-k">{{ fmtDate(item.addTime, 2) }}</div>
          <div class="mr15 cl-blue" @click="replied(item.fbId, index)"><i class="iconfont">&#xea54;</i> 查看</div>
          <div class="mr15 cl-warn" @click="update(item.fbId)"><i class="iconfont">&#xea48;</i> 修改</div>
          <div class="cl-blue" @click="reply(item.fbType, 2, item.fbId)"><i class="iconfont">&#xea7c;</i> 回复</div>
        </div>
        <div class="fb-l" v-for="rep in item.children" :key="rep.fbId">
          <div>管理员回复：</div>
          <div class="fb-i">{{ rep.remarks }}</div>
        </div>
      </div>
      <pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="pages" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="oneModalShow" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 上报意见反馈信息</div>
              <div class="header-right" @click="closeModal(1)"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>意见分类</div>
                <tree-sel :tree-list="typeList" :kind="2" :inboxed="false" :curName="fbForm.typeName ? fbForm.typeName+'['+fbForm.typeCode+']' : ''" pre-name="意见分类" @setValue="setValue" />
              </div>
              <div>
                <div class="ipt-title">意见内容</div>
                <div><textarea v-model="fbForm.remarks" class="desc-txt"></textarea></div>
              </div>
              <div>
                <div class="ipt-title">附件</div>
                <div><sel-file :kind="4" :types="1" :files="imgListRef" @setUrl="setUrl" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>联系电话</div>
                <div><input type="text" v-model="fbForm.phone" maxlength="13" placeholder="请输入联系电话" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>电子邮箱</div>
                <div><input type="text" v-model="fbForm.email" maxlength="100" placeholder="请输入电子邮箱" class="ipt" /></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-pi mr15" @click="save(1)"><i class="iconfont">&#xea90;</i> 保存</div>
              <div class="btn-d" @click="closeModal(1)"><i class="iconfont">&#xea4f;</i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>

    <!-- 回复意见弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="replyModalShow" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 上报意见反馈信息</div>
              <div class="header-right" @click="closeModal(1)"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title">回复内容</div>
                <div><textarea v-model="fbForm.remarks" class="desc-txt"></textarea></div>
              </div>
              <div>
                <div class="ipt-title">附件</div>
                <div><sel-file :kind="4" :types="1" :files="imgListRef" @setUrl="setUrl" /></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-pi mr15" @click="save(2)"><i class="iconfont">&#xea90;</i> 保存</div>
              <div class="btn-d" @click="closeModal(2)"><i class="iconfont">&#xea4f;</i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.fb-a {padding: 10px;}
.fb-b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.fb-c {display: inline-flex; display: -webkit-inline-flex; align-items: center;}
.fb-d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
.fb-e {border: 1px dashed #DDD; padding: 5px 15px 15px 15px; display: flex; display: -webkit-flex; flex-wrap: wrap; margin-bottom: 10px;}
.fb-f {display: inline-flex; display: -webkit-inline-flex;}

.fb-g {padding: 4px 0;}
.fb-h {margin: 4px 8px; box-shadow: 1px 1px 3px #666;}
.fb-i {padding: 15px;}
.fb-j {width: calc(100% - 30px); display: flex; display: -webkit-flex; padding: 15px;}
.fb-k {flex-grow: 1;}

.fb-l {border-top: 1px dashed #DDD; padding: 10px 20px;}
</style>